const gulp = require('gulp');
const connect = require('gulp-connect');
const uglify = require('gulp-uglify');
const clean = require('gulp-clean')
const rename = require("gulp-rename");
const gutil = require('gulp-util');
var browserify = require("browserify");
var babelify    = require('babelify');
var source      = require('vinyl-source-stream');
var buffer      = require('vinyl-buffer');

gulp.task('connect', function() {
  	connect.server({
	    root: './test',
	    port: 3030,
	    livereload: true
  	});
});

gulp.task('html', function () {
  	return gulp.src('./test/*.html')
    	.pipe(connect.reload());
});

gulp.task('babel', function(){
    //通过browserify管理依赖
    return browserify({
            //insertGlobals: true,
            //入口
            entries: './src/index.js', 
            debug: true
        })
        //es6 to es5
        .transform("babelify", {presets: ["@babel/preset-env"],plugins:["@babel/plugin-transform-runtime"]})
        .bundle()
        .pipe(source('web-performance-sdk.js'))
        .pipe(buffer())
        .pipe(uglify({ mangle: false }))//压缩
        .on('error', function (err) {
            gutil.log(gutil.colors.red('[Error]'), err.toString());
        })  
        .pipe(gulp.dest('./test/lib'));
});

gulp.task('watch', function () {
    gulp.watch(['./src/*.js'], gulp.series('babel'));
  	gulp.watch(['./test/lib/web-performance-sdk.js'], gulp.series('html'));
});

gulp.task('build',function(){
      //通过browserify管理依赖
    return browserify({
        //insertGlobals: true,
        //入口
        entries: './src/index.js', 
        debug: false
    })
    //es6 to es5
    .transform("babelify", {presets: ["@babel/preset-env"],plugins:["@babel/plugin-transform-runtime"]})
    .bundle()
    .pipe(source('web-performance-sdk.js'))
    .pipe(buffer())
    .pipe(uglify({ mangle: false }))//压缩
    .on('error', function (err) {
        gutil.log(gutil.colors.red('[Error]'), err.toString());
    })  
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./dist'));  
});

//gulp.parallel('taskA','taskB') 并行
//gulp.series('taskA','taskB') 顺序执行
gulp.task('default', gulp.parallel('babel','connect','watch'));